package com.pollux.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.pollux.constant.JwtClaimsConstant;
import com.pollux.context.BaseContext;
import com.pollux.properties.JwtProperties;
import com.pollux.result.Result;
import com.pollux.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNullApi;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author: pollux
 * @CreateTime: 2024-10-31
 * @Description: jwt令牌拦截类
 * @Version: 1.0
 */

@Component
@Slf4j
public class JwtUserInterception implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1.从请求头获得令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2.校验令牌
        try {
            //解析令牌如何出错就会抛出异常
            Claims claims = JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), token);
            //获得当前用户Id
            BaseContext.setThreadLocal(Integer.parseInt(claims.get(JwtClaimsConstant.USER_ID).toString()));
            //放行
            return true;

        }catch (Exception ex){
            //在这里直接写好了错误信息和状态码，前端只需要判断如果是401的状态码直接退出登录即可

            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
            String json = JSONObject.toJSONString(Result.error("账号未登录"));
            //设置响应头22
            response.setContentType("application/json;charset=utf-8");
            //将状态码设为401，表示token已失效
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //响应
            response.getWriter().write(json);

            return false;
        }
    }
}

































